package net.sudot.commons.security;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 用户MethodArgumentResolver
 *
 * @author tangjialin on 2017-06-14 0014.
 */
public class LoginUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 支持参数
     *
     * @param methodParameter MethodParameter
     * @return 是否支持参数
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(LoginUser.class);
    }

    /**
     * 解析变量
     *
     * @param methodParameter       MethodParameter
     * @param modelAndViewContainer ModelAndViewContainer
     * @param nativeWebRequest      NativeWebRequest
     * @param webDataBinderFactory  WebDataBinderFactory
     * @return 变量
     */
    @SuppressWarnings("unchecked")
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        return nativeWebRequest.getAttribute(LoginUser.class.getSimpleName(), 0);
    }

}